package org.jarx.android.reader;

import java.io.IOException;
import android.app.Activity; 
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;

public class SubListActivity extends ListActivity {

    private static final String TAG = "SubListActivity";
    private static final int DIALOG_MARK_ALL_AS_READ = 1;

    private SubsAdapter subsAdapter;

    private BroadcastReceiver refreshReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            SubListActivity.this.initListAdapter();
        }
    };

    private BroadcastReceiver startReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent intent) {
            String action = intent.getAction();
            boolean busy = intent.getBooleanExtra("busy", true);
            CharSequence text = null;
            if (action.equals(ReaderService.ACTION_START_SYNC_RESULT)) {
                if (busy) {
                    text = getText(R.string.msg_service_busy);
                } else {
                    text = getText(R.string.msg_sync_started);
                }
            }
            if (text != null) {
                ActivityHelper.showToast(c, text);
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IntentFilter filter = new IntentFilter();
        filter.addAction(ReaderService.ACTION_SYNC_SUBS_FINISHED);
        filter.addAction(ReaderService.ACTION_UNREAD_MODIFIED);
        registerReceiver(this.refreshReceiver, filter);

        filter = new IntentFilter();
        filter.addAction(ReaderService.ACTION_START_SYNC_RESULT);
        registerReceiver(this.startReceiver, filter);

        setContentView(R.layout.sub_list);
        initListAdapter();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(this.refreshReceiver);
        unregisterReceiver(this.startReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.sub_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_reload:
            sendBroadcast(new Intent(ReaderService.ACTION_START_SYNC));
            return true;
        case R.id.menu_mark_as_read:
            showDialog(DIALOG_MARK_ALL_AS_READ);
            return true;
        case R.id.menu_prefs:
            startActivityForResult(new Intent(this, PrefActivity.class),
                ActivityHelper.REQUEST_PREFS);
            return true;
        }
        return false;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Long subId = (Long) v.getTag();
        if (subId != null) {
            ActivityHelper.startItemActivityBySubId(this, subId);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ActivityHelper.REQUEST_PREFS) {
            initListAdapter();
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_MARK_ALL_AS_READ:
            return new AlertDialog.Builder(this)
                .setTitle(R.string.txt_reads)
                .setMessage(R.string.msg_confirm_mark_as_read_all)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        progressMarkAllAsRead();
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                }).create();
        }
        return null;
    }

    public void initListAdapter() {
        Context c = getApplicationContext();
        String where = null;
        String orderby = Subscription._NEWEST_ITEM_TIME + " desc";
        if (Prefs.isViewUnreadOnly(c)) {
            where = Subscription._UNREAD_COUNT + " > 0";
        }
        Cursor csr = new Subscription.FilterCursor(managedQuery(
            Subscription.CONTENT_URI, null, where, null, orderby));
        if (this.subsAdapter == null) {
            this.subsAdapter = new SubsAdapter(this, csr);
            setListAdapter(this.subsAdapter);
        } else {
            this.subsAdapter.changeCursor(csr);
        }
    }

    private void progressMarkAllAsRead() {
        final Handler handler = new Handler();
        final long time = System.currentTimeMillis();
        final Context c = getApplicationContext();
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setIndeterminate(true);
        dialog.setMessage(getText(R.string.msg_mark_as_read_running));
        dialog.show();
        new Thread() {
            public void run() {
                ReaderManager rman = ReaderManager.newInstance(c);
                try {
                    rman.syncMarkAllAsRead(time);
                } catch (IOException e) {
                    ActivityHelper.showToast(c, e);
                } catch (ReaderException e) {
                    ActivityHelper.showToast(c, e);
                }
                handler.post(new Runnable() {
                    public void run() {
                        dialog.dismiss();
                    }
                });
            }
        }.start();
    }

    private class SubsAdapter extends ResourceCursorAdapter {

        private SubsAdapter(Context c, Cursor csr) {
            super(c, R.layout.sub_list_row, csr, false);
        }

        @Override
        public void bindView(View view, Context c, Cursor csr) {
            Subscription.FilterCursor subCsr = (Subscription.FilterCursor) csr;

            ImageView iconView = (ImageView) view.findViewById(R.id.icon);
            TextView titleView = (TextView) view.findViewById(R.id.title);
            TextView newestView = (TextView) view.findViewById(R.id.newest);

            Subscription sub = subCsr.getSubscription();
            titleView.setText(ActivityHelper.toLabelWithUnread(sub));

            long newestItemTime = sub.getNewestItemTime();
            if (newestItemTime > 0) {
                newestView.setText(Utils.formatTimeAgo(newestItemTime));
            }

            Bitmap icon = sub.getIcon(SubListActivity.this);
            if (icon == null) {
                iconView.setImageResource(R.drawable.item_read);
            } else {
                iconView.setImageBitmap(icon);
            }

            view.setTag(sub.getId());
        }
    }
}
